﻿using System;
using NUnit.Core;
using NUnit.Util;

namespace QuickTest.Core.TestRunner
{
    /// <summary>
    /// The NUnitTestEventTranslator class handles NUnit events and raises QuickTest TestEvents.
    /// </summary>
    internal class NUnitEventListener : EventListener
    {
        private readonly ITestEvents testEvents;

        internal NUnitEventListener(ITestEvents testEvents)
        {
            this.testEvents = testEvents;
        }

        public void RunStarted(string name, int testCount)
        {
            testEvents.RaiseRunStarted(new TestRunStartedEventArgs(testCount));
        }

        public void RunFinished(NUnit.Core.TestResult result)
        {
            var summary = new SummaryVisitor();
            result.Accept(summary);

            testEvents.RaiseRunFinished(new TestRunFinishedEventArgs(
                                            summary.ResultCount, summary.ResultCount - summary.FailureCount, summary.FailureCount, summary.TestsNotRun));
        }

        public void RunFinished(Exception exception)
        {
        }

        public void TestStarted(TestName testName)
        {
        }

        public void TestFinished(TestCaseResult result)
        {
            ResultState resultState = !result.Executed
                                          ? ResultState.NotRun
                                          : result.IsSuccess ? ResultState.Success : ResultState.Failure;

            var res = new TestResult(result.Name, resultState);

            testEvents.RaiseTestFinished(new TestEventArgs(res));
        }

        public void SuiteStarted(TestName testName)
        {
        }

        public void SuiteFinished(TestSuiteResult result)
        {
        }

        public void UnhandledException(Exception exception)
        {
        }

        public void TestOutput(TestOutput testOutput)
        {
        }
    }
}